package my.edu.api;

import com.alibaba.druid.support.json.JSONUtils;
import my.edu.api.entity.CountryEntity;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class CountryServiceImpl implements CountryService {
    @Override
    public List<String> getProvince(String country) {
        return Arrays.asList(
                "北京市", "天津市", "上海市", "重庆市",
                "河北省", "山西省", "辽宁省", "吉林省", "黑龙江省",
                "江苏省", "浙江省", "安徽省", "福建省", "江西省", "山东省",
                "河南省", "湖北省", "湖南省", "广东省", "海南省",
                "四川省", "贵州省", "云南省", "陕西省", "甘肃省", "青海省",
                "台湾省",
                "内蒙古自治区", "广西壮族自治区", "西藏自治区", "宁夏回族自治区", "新疆维吾尔自治区",
                "香港特别行政区", "澳门特别行政区"
        );
    }

    @Override
    public List<String> getCity(String province) {
        CountryEntity countryEntity = new CountryEntity();
        String url = "https://apis.juhe.cn/fapigw/globalarea/areas";
        String format = String.format("country=%s&province=%s&key=%s", "中国", province, "05b4833774eb58f22e3e4ffba5c964cc");
        //创建请求对象
        HttpGet httpGet = new HttpGet(url + "?" + format);
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {//连接对象
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {//响应对象
                // 获取状态码
                System.out.println(response.getVersion()); // HTTP/1.1
                System.out.println(response.getCode()); // 200
                System.out.println(response.getReasonPhrase()); // OK
                HttpEntity entity = response.getEntity();
                // 获取响应信息
                //countryEntity = JsonUtils.parseObject(EntityUtils.toString(entity), CountryEntity.class);
                String string = EntityUtils.toString(entity);
                countryEntity = (CountryEntity) JSONUtils.parse(string);
            }
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
        System.out.println();
        return countryEntity.getResult().stream().map(CountryEntity.ProvinceEntity::getCity).toList();
    }
}
